package sky.wicket;

import org.apache.wicket.Page;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sky.domain.City;
import sky.service.CityService;
import sky.service.CountryService;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 06.10.13
 * Time: 15:23
 * To change this template use File | Settings | File Templates.
 */
public class AddUpdateCity extends BasePage {

    @SpringBean
    private CityService cityService;
    @SpringBean
    private CountryService countryService;

    private City city;
    private boolean createFlag = false;
    private boolean updateFlag = false;
    static final Logger log = LoggerFactory.getLogger(AddUpdateCity.class);

    public AddUpdateCity() {
        city = new City();
        createFlag = true;
        addElementsToPage();
    }

    public AddUpdateCity(String cityName) {
        this.city = cityService.getCityByName(cityName);
        updateFlag = true;
        addElementsToPage();
    }

    private void addElementsToPage() {
        Form<City> newCityForm = new Form<City>("newCityForm", new CompoundPropertyModel<City>(city)) {

            @Override
            protected void onSubmit() {
                log.info("Submitting Form...");
                log.info("Information From Form:");
                log.info("   City's Name: " + city.getName());
                log.info("   City's Country Name: " + city.getCountry().getName());
                if (countryService.getCountryByName(city.getName())!=null) {
                    //airportService.addAirport(airport);
                    log.info("Form Submitted");
                    createOrUpdate();
                } else {
                    error("Cannot submit form");
                }
            }

            @Override
            protected void onError() {}
        };
        newCityForm.add(new TextField<String>("name").setRequired(true));
        newCityForm.add(new TextField<String>("country.name").setRequired(true));
        newCityForm.add(new Label("cityNameLabel", "City: "));
        newCityForm.add(new Label("countryNameLabel", "Country: "));
        add(newCityForm);
        add(new FeedbackPanel("feedback"));
    }

    private void createOrUpdate() {
        log.info("Checking Flags...");
        log.info("Create Flag: " + createFlag);
        log.info("Update Flag: " + updateFlag);
        if (createFlag) {
            cityService.addCity(city);
            return;
        }
        if (updateFlag) {
            cityService.editCity(city);
            return;
        }
    }
}
